import { initPage, PostApi } from '../../utils/util'
import { Promisify } from '../../utils/wxapi'

initPage({
	/**
	 * 页面的初始数据
	 */
	data: {},
	onLoad: function(options) {},
	onShareAppMessage: function() {},
	// 获取用户信息
	onGotUserInfo: function(e) {
		console.log(e.detail.errMsg)
		// console.log(e.detail.userInfo)
		// console.log(e.detail.rawData)
		// if (e.detail.errMsg == 'getUserInfo:ok') {
		// 	return Promisify(wx.getUserInfo)({
		// 		withCredentials: true
		// 	})
		// 		.then(res => {
		// 			console.log(res)
		// 			return PostApi(
		// 				'/weapp/user/dontbind',
		// 				Object.assign({}, res)
		// 			)
		// 		})
		// 		.catch(err => {
		// 			console.log(err)
		// 		})
		// }
		return Promisify(wx.login)().then(res => {
			if (res.code) {
				return PostApi(this.app.globalData.config.fetch_token_url, {
					code: res.code
				}).then(
					data => {
						return data.token
					},
					err => {
						switch (err.errcode) {
							case 2:
								return Promisify(wx.getUserInfo)({
									withCredentials: true
								})
									.then(res => {
										return PostApi(
											'/weapp/user/dontbind',
											Object.assign({}, res, {
												session_key: err.session_key
											})
										).then(() => {
											return this.fetchToken()
										})
									})
									.catch(err => {
										console.log(err)
									})
								break
							default:
								return res.code
						}
					}
				)
			} else {
				return goError(102, '获取登录状态失败', res.errMsg)
			}
		})
	}
})
